<?php
require_once(dirname(dirname(dirname(__FILE__))) . '/app.php');
need_manager();

$id = abs(intval($_GET['id']));
$ads = $eads = Table::Fetch('page_ad', $id);


if ( is_get() && empty($ads) ) {
	$ads = array();
	$ads['id'] = 0;
	$ads['begin_time'] = strtotime('+1 days');
	$ads['end_time'] = strtotime('+8 days'); 
	$ads['end_time'] = strtotime('+8 days'); 
	$ads['url'] = 'http://#'; 
	$ads['user_id'] = $login_user_id; 
}
else if ( is_post() ) {
	$ads = $_POST;
	//print_r($ads);exit;
	$insert = array(
		'image', 'title', 'url', 'position', 'begin_time', 'end_time', 'city_id', 'user_id', 'sort_order', 	
	);

	$ads['user_id'] = $login_user_id;
	$ads['begin_time'] = strtotime($ads['begin_time']);
	$ads['end_time'] = strtotime($ads['end_time']);
	$ads['sort_order'] = abs(intval($ads['sort_order']));
	$ads['position'] = strval($ads['position']);
	$ads['image'] = upload_image('upload_image',$eads['image'],'ads');
	if($ads['city_id'] == ''){$ads['city_id'] = 0;}
	//dbx($ads);exit;
	$insert = array_unique($insert);
	$table = new Table('page_ad', $ads);

	if ( $ads['id'] && $ads['id'] == $id ) {
		$table->SetPk('id', $id);
		$table->update($insert);
		Session::Set('notice', '编辑广告信息成功');
		redirect( WEB_ROOT . "/manage/ad/index.php");
	} 
	else if ( $ads['id'] ) {
		Session::Set('error', '非法编辑');
		redirect( WEB_ROOT . "/manage/ad/index.php");
	}

	if ( $table->insert($insert) ) {
		Session::Set('notice', '新建广告成功');
		redirect( WEB_ROOT . "/manage/ad/index.php");
	}
	else {
		Session::Set('error', '编辑广告失败');
		redirect(null);
	}
}

//查出所有城市
$citys = DB::LimitQuery('category', array(
			'condition' => array( 'zone' => 'city', ),'order' => 'ORDER BY `sort_order` DESC, `id` DESC',
			));
$selector = 'edit';
include template('manage_ad_edit');
